﻿using System;
using System.IO;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace RockPaperScissors.Web.admin
{
    public partial class Teams : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Membership.GetUser().UserName.ToLower() != "administrator")
                Response.Redirect("~/default.aspx");

            if (!Page.IsPostBack)
                LoadTeams();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveTeam(txtTeamName.Text, txtPassword.Text);
            ClearForm();
        }

        protected void btnCommandHandler_Command(object sender, CommandEventArgs e)
        {
            string userName = e.CommandArgument.ToString();
            string cmd = e.CommandName.ToString();
           
            switch (cmd.ToLower())
            {
                case "delete":
                    // try to delete the user
                    DeleteTeam(userName);

                    LoadTeams();
                    break;
                default:
                    break;
            }
        }

        private void ClearForm()
        {
            txtTeamName.Text = string.Empty;
            txtPassword.Text = string.Empty;
        }

        private void CreateTeamDirectory(string teamName)
        {
            string pathToNewDirectory = Server.MapPath(string.Format("/bots/{0}", teamName));
            Directory.CreateDirectory(pathToNewDirectory);
        }

        private void DeleteTeam(string teamName)
        {
            // try to delete the user
            if (Membership.DeleteUser(teamName) == false)
                this.Master.AddMessage("Error while trying to remove the team.", Message.Styles.Alert); 

            //TODO: should delete the team directory as well
            LoadTeams();
        }

        private void LoadTeams()
        {
            MembershipUserCollection users = Membership.GetAllUsers();

            rptTeamList.DataSource = users;
            rptTeamList.DataBind();
        }

        private void SaveTeam(string name, string password)
        {
            MembershipCreateStatus status;
            MembershipUser user = Membership.CreateUser(name, password,"none@none.com","none","none",true,out status);

            if (status == MembershipCreateStatus.Success)
            {
                this.Master.AddMessage("The team has been added.", Message.Styles.Notice);

                CreateTeamDirectory(name);
                LoadTeams();
            }
            else
            {
                this.Master.AddMessage("Error creating team. Check password strength.", Message.Styles.Alert);
                ClearForm();
            }
        }
    }
}